﻿using ImageUpload.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;

/// <summary>
/// 技术交流qq群：1158377441
/// </summary>
namespace ImageUpload.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;


        private readonly Microsoft.AspNetCore.Hosting.IHostingEnvironment _hostingEnvironment;

        public HomeController(ILogger<HomeController> logger, Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnvironment)
        {
            _logger = logger;
            _hostingEnvironment = hostingEnvironment;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }



        /// <summary>
        /// form表单上传，无法预览，上传之后会跳转页面
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        [HttpPost("Photos")]
        public async Task<IActionResult> UploadPhotosAsync(IFormFileCollection files)
        {
            var fileFolder = Path.Combine(_hostingEnvironment.ContentRootPath, "Photos");
            IFormFile f = Request.Form.Files[0];
            if (f.Length > 0)
            {
                var fileName = DateTime.Now.ToString("yyyyMMddHHmmss") +
                               Path.GetExtension(f.FileName);
                var filePath = Path.Combine(fileFolder, fileName);

                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await f.CopyToAsync(stream);
                }
            }
            long size = files.Sum(f => f.Length);


            if (!Directory.Exists(fileFolder))
                Directory.CreateDirectory(fileFolder);

            foreach (var file in files)
            {
                if (file.Length > 0)
                {
                    var fileName = DateTime.Now.ToString("yyyyMMddHHmmss") +
                                   Path.GetExtension(file.FileName);
                    var filePath = Path.Combine(fileFolder, fileName);

                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }
                }
            }

            return Ok(new { count = files.Count, size });
        }

        /// <summary>
        /// jq-ajax上传，可上传前预览
        /// </summary>
        /// <returns></returns>
        [HttpPost("img-jq")]
        public async Task<IActionResult> UploadPhotosAsyncWithJq()
        {
            var fileFolder = Path.Combine(_hostingEnvironment.ContentRootPath, "Photos");
            IFormFile f = Request.Form.Files[0];
            if (f.Length > 0)
            {
                var fileName = DateTime.Now.ToString("yyyyMMddHHmmss") +
                               Path.GetExtension(f.FileName);
                var filePath = Path.Combine(fileFolder, fileName);

                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await f.CopyToAsync(stream);
                }
            }

            return Ok(new { count = 1 });
        }

    }
}